package com.demo.homework;

import javax.sound.midi.Soundbank;
import java.util.Scanner;

/**
 * @author gy
 * @date 2022/4/24
 */
public class HomeWork01 {
    public static void main(String[] args) {
        A a = new A();
        B b = new B(a);
        a.start();
        b.start();
    }
}

class A extends Thread {

    private boolean loop = true;

    /**
     * 该线程循环随机打印 1-100
     */
    @Override
    public void run() {
        while (loop) {
            System.out.println((int) (Math.random() * 100 + 1));
            try {
                Thread.sleep(2*1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("A 线程退出");
    }

    public void setLoop(boolean loop) {
        this.loop = loop;
    }
}

class B extends Thread {
    /**
     * 让 B 线程 持有 A线程，去控制A线程
     */
    private A a;


    public B(A a) {
        this.a = a;
    }

    @Override
    public void run() {

        while (true) {
            System.out.println("请输入 'Q' 退出:");
            // 注意：在输入完毕之后，一定要记得敲回车
            Scanner scanner = new Scanner(System.in);

            char c = scanner.next().toUpperCase().charAt(0);

            if (c == 'Q') {
                a.setLoop(false);
                break;
            }
        }
        System.out.println("B 线程退出");
    }
}
